package com.moyq5.wifi.joystick;

import android.content.Intent;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.UnknownFormatConversionException;

/**
 * 控制台日志输出
 * @author mo_yq5
 * @since 2021/11/23
 */
public class ConsoleDefault implements Console {
    private final String TAG;
    public ConsoleDefault(Class<?> clazz) {
        this.TAG = clazz.getSimpleName();
    }

    @Override
    public void debug(String format, Object... args) {
        String message = format(format, args);
        Log.i(TAG, message);
        sendConsole(DEBUG, TAG, message);
    }

    @Override
    public void info(String format, Object... args) {
        String message = format(format, args);
        Log.i(TAG, message);
        sendConsole(INFO, TAG, message);
    }

    @Override
    public void warn(String format, Object... args) {
        String message = format(format, args);
        Log.w(TAG, message);
        sendConsole(WARN, TAG, message);
    }

    @Override
    public void error(String format, Object... args) {
        String message = format(format, args);
        Log.e(TAG, message);
        sendConsole(ERROR, TAG, message);
    }

    @Override
    public void error(Throwable cause, String format, Object... args) {
        String message = format(format, args);
        Log.e(TAG, message, cause);
        try (ByteArrayOutputStream os = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(os)) {
            ps.println(message);
            cause.printStackTrace(ps);
            message = os.toString("UTF-8");
        } catch (Exception e) {
            Log.e(TAG, "error: ", e);
        }
        sendConsole(ERROR, TAG, message);
    }

    private String format(String format, Object... args) {
        if (null != args && args.length > 0) {
            try {
                format = String.format(format, args);
            } catch (UnknownFormatConversionException ignored) {

            }
        }
        return format;
    }

    private static void sendConsole(int level, String tag, String message) {
        Intent intent = new Intent(Console.class.getName());
        intent.putExtra(PARAM_LEVEL, level);
        intent.putExtra(PARAM_MESSAGE, tag + ": " + message);
        App.localSend(App.getInstance(), intent);
    }
}
